/**
 * Copyright (c) 2006-2007 Jinyi.lu
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of GNU LGPL license by gun.org
 * which accompanies this distribution, and is available at
 * http://gnu.feld-it.at/copyleft/lesser.html
 * 
 * Project Homepage : http://code.google.com/p/demou
 * Source Code: svn checkout http://demou.googlecode.com/svn/trunk/ demou
 * Mailing list : jinyi.lu@gmail.com
 *                stonelu@126.com
 *
 *  
 * Contributors:
 *     JinYi.Lu - initial API and implementation
 */
package cn.tworen.demou.remoting.amf;

import java.io.IOException;

import net.sf.cindy.Buffer;

import org.apache.log4j.Logger;

import cn.tworen.demou.amf.Amf0Decode;
import cn.tworen.demou.remoting.AmfMessage;
import cn.tworen.demou.remoting.Body;
import cn.tworen.demou.remoting.Header;

/**
 * Created on  2007-2-26
 *
 * Title       : AmfDecode.java
 * Description : 
 * 
 * @author     : LuJinYi
 * @version    : 1.0
 * @Date       : 2007-2-26
 * History     : 
 * 
 */
public class AmfDecode extends Amf0Decode {
	private static final Logger logger = Logger.getLogger(AmfDecode.class);
	public AmfMessage decode(Buffer bufferContext) throws IOException {
		this.resetTable();
		AmfMessage message = new AmfMessage();
		this.setBuffer(bufferContext);
		int version = buffer.getUnsignedShort();
		message.setVersion(version);
		logger.debug("version=" + version);
		int headerCount = buffer.getUnsignedShort();
		logger.debug("headerCount=" + headerCount);

		for (int i = 0; i < headerCount; i++) {
			Header header = new Header();
			message.getHeaders().add(header);
			String name = this.readString();
			header.setName(name);
			boolean mustUnderstand = buffer.get() == 0?false:true;
			header.setMustUnderstand(mustUnderstand);
			int length = buffer.getInt();
			logger.debug("name=" + name + " understand=" + mustUnderstand + " lenght=" + length);
			Object data = null;
			try {
				data = this.readObject();
				logger.debug("data=" + data);
			} catch (Exception ex) {
				data = ex;
			}
			header.setValue(data);			
		}

		int bodyCount = buffer.getUnsignedShort();
		logger.debug("bodyCount=" + bodyCount);
		for (int i = 0; i < bodyCount; i++) {
			Body body = new Body();
			message.getBodies().add(body);
			String targetURI = this.readString();
			body.setTargetURI(targetURI);
			String responseURI = this.readString();
			body.setResponseURI(responseURI);
			int length = buffer.getInt();
			logger.debug("targetURI=" + targetURI + " responseURI=" + responseURI + " lenght=" + length);
			Object data = null;
			try {
				data = this.readObject();
			} catch (Exception ex) {
				data = ex;
				ex.printStackTrace();
			}
			body.setValue(data);
		}
		return message;
	}
}
